package com.lykj.llw.box.ui.activity

import android.content.Intent
import android.os.Bundle
import android.support.v4.os.IResultReceiver._Parcel
import android.util.Log
import android.view.View
import android.widget.TextView
import androidx.recyclerview.widget.LinearLayoutManager
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.listener.OnItemChildClickListener
import com.chad.library.adapter.base.listener.OnItemClickListener
import com.gyf.immersionbar.BarHide
import com.gyf.immersionbar.ImmersionBar
import com.lykj.lib_base.base.BaseActivity
import com.lykj.lib_base.bus.FlowBus
import com.lykj.lib_base.constants.BConstants
import com.lykj.lib_base.internal.extfun.clickWithTrigger
import com.lykj.lib_base.internal.inter.OnConfirmClickListener
import com.lykj.lib_base.internal.utils.PackageUtils
import com.lykj.lib_base.internal.utils.ToastUtils
import com.lykj.llw.box.R
import com.lykj.llw.box.adapter.DownloadManagerAdapter
import com.lykj.llw.box.data.model.LocalDownloadRecordModel
import com.lykj.llw.box.databinding.ActDownloadManagerBinding
import com.lykj.llw.box.ui.diafrg.ConfirmDiaFrg
import com.lykj.llw.box.utils.DownloadManagerUtils
import java.io.File

/**
 * ================================================
 * 下载管理
 * ================================================
 *
 * @author gosha
 * @date 2023/12/1-14:21
 */
class DownloadManagerActivity : BaseActivity() {
    lateinit var binding: ActDownloadManagerBinding

    private var isCancel = false
    private val mData = ArrayList<LocalDownloadRecordModel>()
    private var mAdapter = DownloadManagerAdapter()
    private var mCurrentTime = 0L
    private val TAG = "DownloadManagerActivity"

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        binding = ActDownloadManagerBinding.inflate(layoutInflater)
        setContentView(binding.root)
        initUI()
        initData()
        setListener()
    }

    override fun initUI() {
        binding.titleBar.tvTitle.text = "下载管理"
        binding.titleBar.tvRightOption.text = "管理"

        initRCV()

        mCurrentTime = System.currentTimeMillis()
        FlowBus.withStick<LocalDownloadRecordModel>(BConstants.BUS_KEY.DOWNLOAD_REFRESH)
            .register(this) {
                //FIXME:每隔一秒刷新数据
                //刷新数据

                for ((index, m) in mData.withIndex()) {
                    if (it.gameId == m.gameId) {
                        m.currentBytes = it.currentBytes
                        m.totalBytes = it.totalBytes
                        m.status = it.status

                        mAdapter.notifyItemChanged(index)
                        break
                    }
                }
            }
    }

    private fun initRCV() {
        val linearLayoutManager = LinearLayoutManager(this)
        linearLayoutManager.orientation = LinearLayoutManager.VERTICAL
        binding.rcvLocal.layoutManager = linearLayoutManager
        binding.rcvLocal.setHasFixedSize(true)
        mAdapter.data = mData
        mAdapter.addChildClickViewIds(R.id.tv_btn_option, R.id.iv_delete)
        mAdapter.setOnItemClickListener { _, _, position ->
            val intent = Intent(this, GameDetailActivity::class.java)
            intent.putExtra("gid", mData[position].gameId)
            startActivity(intent)
        }
        mAdapter.setOnItemChildClickListener { _, view, position ->
            when (view.id) {
                R.id.tv_btn_option -> {
                    when ((view as TextView).text) {
                        "打开" -> {
                            //打开应用
                            try {
                                val intent =
                                    packageManager.getLaunchIntentForPackage(mData[position].packageName)
                                startActivity(intent)
                            } catch (e: Exception) {
                                e.printStackTrace()
                            }
                        }

                        "安装" -> {
                            val path = "${mData[position].path}/${mData[position].gameId}.apk"
                            if (File(path).exists()) {
                                PackageUtils.installApk(
                                    this@DownloadManagerActivity,
                                    "${mData[position].path}/${mData[position].gameId}.apk"
                                )
                            } else {
                                ToastUtils.showShort(this@DownloadManagerActivity, "安装包不存在")
                            }
                        }

                        "下载" -> {

                        }
                    }
                }

                R.id.iv_delete -> {
                    if (isCancel) {
                        runOnUiThread {
                            ConfirmDiaFrg()
                                .setOnConfirmListener(object : OnConfirmClickListener {
                                    override fun onSure() {
                                        DownloadManagerUtils.getCallFromGameId(mData[position].gameId)
                                            ?.cancel()
                                        DownloadManagerUtils.getDownloadInfo()
                                            .remove(mData[position])
                                        DownloadManagerUtils.writeDownloadToLocal()
                                        mData.removeAt(position)
                                        mAdapter.notifyDataSetChanged()
                                        Log.e(TAG, "停止下载并删除任务")
                                    }

                                    override fun onCancel() {
                                    }
                                }).show(supportFragmentManager, "确认弹窗")
                        }
                    }
                }
            }
        }
        binding.rcvLocal.adapter = mAdapter
    }

    override fun initData() {
    }

    override fun onResume() {
        super.onResume()

        ImmersionBar.with(this).statusBarDarkFont(true) //状态栏字体是深色，不写默认为亮色
            .navigationBarDarkIcon(true).hideBar(BarHide.FLAG_HIDE_NAVIGATION_BAR)
            .navigationBarEnable(false).init()

        mData.clear()
        mData.addAll(DownloadManagerUtils.getDownloadInfoFromLocal())
        mAdapter.notifyDataSetChanged()
    }

    override fun setListener() {
        binding.titleBar.ivBack.clickWithTrigger {
            finish()
        }

        binding.titleBar.tvRightOption.clickWithTrigger(220) {
            isCancel = !isCancel
            if (isCancel) {
                binding.titleBar.tvRightOption.text = "取消"

                mData.forEach {
                    it.isManagerModel = true
                }
            } else {
                binding.titleBar.tvRightOption.text = "管理"
                mData.forEach {
                    it.isManagerModel = false
                }
            }

            mAdapter.notifyDataSetChanged()
        }
    }

    override fun onDestroy() {
        super.onDestroy()
    }
}